import { defineStore } from 'pinia'
import { getAddressList, updateAddress } from '@/api/address.js'

export const useAddressStore = defineStore('address', {
    state: () => {
        return {
            data: [],
            list: [],
        }
    },
    actions: {
        async getAddressInfo(page = 1, limit = 10) {
            const res = await getAddressList({ page, limit });
            if (res.code === 1) {
                this.list = res.data.list
                //过滤数据，使其符合vant地址组件需要的格式,没有地址列表会为null，null没有map方法会报错。
                this.data = (res.data.list ?? []).map((item) => {
                    return {
                        id: item.id,
                        name: item.name,
                        tel: item.phone,
                        address: item.province + item.city + item.town + item.detail,
                        isDefault: item.is_default == 1 ? true : false,
                    };
                });
            }
        },
        //取消上一个默认地址的选中状态
        async setAddressInfo() {
            let obj = this.list.find(item => {
                return item.is_default == '1'
            })
            //如果obj没有值说明没有默认地址
            if (obj) {
                await updateAddress({
                    id: obj.id,
                    is_default: '0',
                    name: obj.name,
                    phone: obj.phone,
                    province: obj.province,
                    city: obj.city,
                    town: obj.town,
                    street: obj.street,
                    detail: obj.detail,
                })
            }
        },
        //当前点击地址默认选中状态改为true,这个方法作废了
        /*  async editAddressInfo(res) {
             let obj = this.list.find(item => {
                 return item.id == res.id
             })
             await updateAddress({
                 id: obj.id,
                 is_default: '1',
                 name: obj.name,
                 phone: obj.phone,
                 province: obj.province,
                 city: obj.city,
                 town: obj.town,
                 street: obj.street,
                 detail: obj.detail,
             })
         } */
    }
})